<template>
  <div class="system-bg">
    <el-card class="user-card" shadow="hover">
      <div slot="header" class="card-header-vertical">
        <div class="header-title">菜单管理</div>
        <div class="header-btn-group right">
          <el-button class="add-btn" type="primary" @click="onShowAdd">
            <i class="el-icon-plus"></i> 新增菜单
          </el-button>
          <el-button class="delete-btn" type="danger" :disabled="!multipleSelection.length" @click="batchRemove">
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
        </div>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-bar">
        <el-form-item label="菜单名称">
          <el-input v-model="searchForm.name" placeholder="菜单名称" size="small" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部" size="small">
            <el-option label="全部" :value="''" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="父级菜单">
          <el-select v-model="searchForm.parentId" placeholder="全部" size="small">
            <el-option label="全部" :value="''" />
            <el-option v-for="menu in parentMenus" :key="menu.id" :label="menu.name" :value="menu.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="menuTable"
        :data="list"
        style="width:100%"
        class="user-table"
        highlight-current-row
        row-key="id"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="70" align="center" />
        <el-table-column prop="name" label="菜单名称" width="150" />
        <el-table-column prop="path" label="菜单路径" width="200" />
        <el-table-column prop="component" label="组件路径" width="200" />
        <el-table-column prop="icon" label="图标" width="100" />
        <el-table-column prop="parentId" label="父菜单" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.parentId === 0">顶级菜单</span>
            <span v-else>{{ getParentName(scope.row.parentId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="90">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button size="mini" class="edit-btn" @click="edit(scope.row)">编辑</el-button>
            <el-button size="mini" class="delete-btn" type="danger" @click="remove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :total="total"
        :page-size="size"
        :current-page="current"
        @current-change="load"
        @size-change="handleSizeChange"
        layout="total, prev, pager, next, jumper, ->, sizes"
        :page-sizes="[10, 20, 50, 100]"
        class="user-pagination"
      />
    </el-card>
    
    <!-- 新增/编辑菜单弹窗 -->
    <el-dialog :visible.sync="showDialog" :title="dialogTitle" class="fade-dialog custom-dialog" :close-on-click-modal="false" width="500px">
      <el-form :model="form" label-width="90px" class="dialog-form">
        <el-form-item label="菜单名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="菜单路径">
          <el-input v-model="form.path" />
        </el-form-item>
        <el-form-item label="组件路径">
          <el-input v-model="form.component" />
        </el-form-item>
        <el-form-item label="图标">
          <el-select v-model="form.icon" placeholder="请选择图标" filterable style="width: 100%;">
            <el-option
              v-for="icon in iconOptions"
              :key="icon"
              :label="icon"
              :value="icon"
            >
              <i :class="icon" style="margin-right:8px;"></i>{{ icon }}
            </el-option>
          </el-select>
          <div v-if="form.icon" style="margin-top:8px;">
            <span>预览：</span><i :class="form.icon" style="font-size:20px;vertical-align:middle;"></i>
          </div>
        </el-form-item>
        <el-form-item label="父菜单">
          <el-tree
            :data="parentMenusTree"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            highlight-current
            accordion
            :expand-on-click-node="false"
            :default-expanded-keys="[form.parentId]"
            :current-node-key="form.parentId"
            @node-click="onParentMenuSelect"
            style="width:100%; border:1px solid #e4e7ed; border-radius:4px; padding:8px;"
          >
            <span slot-scope="{ node, data }">
              <span>{{ data.name }}</span>
            </span>
          </el-tree>
          <div v-if="form.parentId === 0" style="margin-top:8px; color:#999;">当前为顶级菜单</div>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sortOrder" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMenuList, addMenu, updateMenu, deleteMenu } from '@/api/menu';

export default {
  name: 'SystemMenu',
  data() {
    return {
      list: [],
      total: 0,
      size: 10,
      current: 1,
      showDialog: false,
      isEdit: false,
      dialogTitle: '新增菜单',
      form: {
        name: '',
        path: '',
        component: '',
        icon: '',
        parentId: 0,
        sortOrder: 0,
        status: 1
      },
      parentMenus: [],
      searchForm: {
        name: '',
        status: '',
        parentId: ''
      },
      multipleSelection: [],
      iconOptions: [],
      parentMenusTree: [],
      currentRow: null
    };
  },
  created() {
    this.load();
    // 自动收集所有el-icon-xxx的class
    const iconList = [];
    for (const sheet of document.styleSheets) {
      try {
        for (const rule of sheet.cssRules) {
          if (rule.selectorText && rule.selectorText.startsWith('.el-icon-')) {
            const match = rule.selectorText.match(/\.el-icon-([a-zA-Z0-9-]+)/);
            if (match) {
              const iconName = 'el-icon-' + match[1];
              if (!iconList.includes(iconName)) {
                iconList.push(iconName);
              }
            }
          }
        }
      } catch (e) {
        // 某些样式表可能跨域，忽略
      }
    }
    this.iconOptions = iconList.sort();
  },
  methods: {
    async load(page = 1) {
      this.current = page;
      const params = {
        page,
        size: this.size,
        ...this.searchForm
      };
      const data = await getMenuList(params);
      this.list = data.records;
      this.total = data.total;
      this.size = data.size;
      this.current = data.current;
      
      // 加载父菜单选项
      this.loadParentMenus();
    },
    handleSizeChange(newSize) {
      this.size = newSize;
      this.load(1);
    },
    async loadParentMenus() {
      try {
        const data = await getMenuList({ page: 1, size: 1000 });
        this.parentMenus = data.records || [];
        this.parentMenusTree = this.buildMenuTree(this.parentMenus);
      } catch (error) {
        console.error('加载父菜单失败:', error);
      }
    },
    buildMenuTree(list) {
      const map = {};
      list.forEach(item => { map[item.id] = { ...item, children: [] }; });
      const tree = [];
      list.forEach(item => {
        if (item.parentId && item.parentId !== 0 && map[item.parentId]) {
          map[item.parentId].children.push(map[item.id]);
        } else {
          tree.push(map[item.id]);
        }
      });
      // 添加顶级菜单选项
      tree.unshift({ id: 0, name: '顶级菜单', children: [] });
      return tree;
    },
    onParentMenuSelect(node) {
      this.form.parentId = node.id;
    },
    getParentName(parentId) {
      const parent = this.parentMenus.find(menu => menu.id === parentId);
      return parent ? parent.name : '';
    },
    onShowAdd() {
      this.isEdit = false;
      this.dialogTitle = '新增菜单';
      this.form = {
        name: '',
        path: '',
        component: '',
        icon: '',
        parentId: 0,
        sortOrder: 0,
        status: 1
      };
      this.showDialog = true;
    },
    edit(row) {
      this.isEdit = true;
      this.dialogTitle = '编辑菜单';
      this.form = { ...row };
      this.showDialog = true;
    },
    async save() {
      try {
        if (this.isEdit) {
          await updateMenu(this.form.id, this.form);
          this.$message.success('菜单更新成功');
        } else {
          await addMenu(this.form);
          this.$message.success('菜单添加成功');
        }
        this.showDialog = false;
        this.load();
      } catch (error) {
        console.error('保存菜单失败:', error);
        this.$message.error('保存菜单失败');
      }
    },
    async remove(row) {
      try {
        await this.$confirm('确定要删除该菜单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await deleteMenu(row.id);
        this.$message.success('菜单删除成功');
        this.load();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除菜单失败:', error);
          this.$message.error('删除菜单失败');
        }
      }
    },
    async batchRemove() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请选择要删除的菜单');
        return;
      }
      try {
        await this.$confirm(`确定要删除选中的 ${this.multipleSelection.length} 个菜单吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const ids = this.multipleSelection.map(item => item.id);
        await deleteMenu(ids); // 假设 deleteMenu 支持批量删除
        this.$message.success('批量删除成功');
        this.load();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error);
          this.$message.error('批量删除失败');
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleRowClick(row) {
      this.currentRow = row;
      this.$refs.menuTable.clearSelection();
      this.$refs.menuTable.toggleRowSelection(row, true);
    },
    onSearch() {
      this.current = 1; // 搜索时重置当前页为1
      this.load();
    },
    onReset() {
      this.searchForm = {
        name: '',
        status: '',
        parentId: ''
      };
      this.load();
    }
  }
};
</script>

<style scoped>
.system-bg {
  min-height: 80vh;
  background: linear-gradient(135deg, #f4f6fa 60%, #e0e7ff 100%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 48px 0;
  animation: fadeIn 0.8s;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(30px);}
  to { opacity: 1; transform: none;}
}
.user-card {
  width: 1100px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.10);
  background: rgba(255,255,255,0.95);
  transition: box-shadow 0.3s;
}
.card-header-vertical {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  padding-bottom: 8px;
}
.header-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
}
.header-btn-group {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background: none;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
}
.header-btn-group.right {
  justify-content: flex-end;
}
.header-btn-group .el-button {
  margin-right: 8px;
  height: 34px;
  font-size: 15px;
  padding: 0 18px;
  display: flex;
  align-items: center;
}
.header-btn-group .el-button:last-child {
  margin-right: 0;
}
.add-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
}
.add-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}
.user-table {
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 18px;
}
.user-table ::v-deep .el-table__row:hover {
  background: #f0f7ff !important;
  transition: background 0.2s;
}
.edit-btn {
  background: #fff;
  border: 1px solid #6a82fb;
  color: #6a82fb;
  margin-right: 8px;
  transition: all 0.2s;
}
.edit-btn:hover {
  background: #6a82fb;
  color: #fff;
}
.delete-btn {
  background: #fff;
  border: 1px solid #fc5c7d;
  color: #fc5c7d;
  transition: all 0.2s;
}
.delete-btn:hover {
  background: #fc5c7d;
  color: #fff;
}
.user-pagination {
  margin-top: 18px;
  text-align: right;
}
.user-pagination ::v-deep .el-pager li {
  border-radius: 6px;
  transition: background 0.2s;
}
.user-pagination ::v-deep .el-pager li.active {
  background: #6a82fb;
  color: #fff;
}
.fade-dialog ::v-deep .el-dialog__wrapper {
  animation: fadeIn 0.4s;
}
.custom-dialog ::v-deep .el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  background: #fafdff;
  padding-bottom: 0;
}
.dialog-form {
  padding: 12px 0 0 0;
}
.dialog-form ::v-deep .el-form-item {
  margin-bottom: 22px;
}
.dialog-footer {
  text-align: right;
  padding: 8px 0 8px 0;
}
.dialog-footer .el-button {
  min-width: 80px;
  border-radius: 6px;
  font-weight: 500;
  margin-left: 8px;
}
.dialog-footer .el-button--primary {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
}
.dialog-footer .el-button--primary:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}
.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: transparent;
  border-radius: 8px;
  border: none;
}
</style> 